using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Topics.Radical.Linq;

namespace Command.Host.Infrastructure
{
    public class DependencyInjectionServiceBehavior  : IServiceBehavior
    {
        private readonly IServiceProvider _serviceProvider;

        public DependencyInjectionServiceBehavior(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            serviceHostBase
                .ChannelDispatchers
                .OfType<ChannelDispatcher>()
                .SelectMany(d => d.Endpoints)
                .ForEach(d => d.DispatchRuntime.InstanceProvider = new DependencyInjectionInstanceProvider(_serviceProvider, serviceDescription.ServiceType));
        }
    }
}